<?php
class Search extends Tut_Model {
    
    public function __construct() {
        parent::__construct();
        $this->_load();
    }

    public function add(array $aProduct) {
        if (empty($aProduct)) {
            return false;
        }

        $aProduct = $this->_prepareArr($aProduct);
        if ((bool) $this->db->insert('product', $aProduct)) {
            return $aProduct;
        }

        return false;
    }

    public function edit(array $aProduct) {
        if (empty($aProduct)) {
            return false;
        }

        //Get id product because after prepareArr, it's going to unset.
        $iId = $aProduct['id'];
        $aProduct = $this->_prepareArr($aProduct, true);
        if ((bool) $this->db->update('product', $aProduct, array('id' => $iId))) {
            return $aProduct;
        }

        return false;
    }

    public function save($iId, $iUserId) {
        if (empty($iId) || empty($iUserId)) {
            return false;
        }

        $aSavedProduct = array(
            'user_id' => $iUserId,
            'product_id' => $iId,
            'date' => time()
        );

        if ((bool) $this->db->insert('saved_product', $aSavedProduct)) {
            return $iId;
        }

        return false;
    }

    public function delete($aIds) {
        if (empty($aIds)) {
            return false;
        }
        
        $this->db->where_in('id', array_values($aIds));
        $this->db->update('product', array('is_deleted' => 1));

        if ($this->db->affected_rows() > 0) {
            return true;
        }

        return false;
    }

    public function getById($iId = 0, $bIsCheckActive = true) {
        if (empty($iId)) {
            return false;
        }

        $this->db->select('p.*, pc.name as product_category, le.name as level, l.name as language')
                ->from('product as p')
                ->join('product_category as pc', 'p.product_category_id = pc.id')
                ->join('language as l', 'p.language_id = l.id')
                ->join('level le', 'p.level_id = le.id')
                ->where('p.id', $iId);

        if ($bIsCheckActive) {
            $this->db->where('p.is_actived', ACTIVE);
        }

        $product = $this->db->get();

        if ($product->num_rows() > 0) {
            $product = $product->row();
            $product->date = date('Y-m-d', $product->date);

            return $product;
        }

        return false;
    }
    
    public function getByCategoryId($iCategoryId, $bIsCheckActive = false){
        if (empty($iCategoryId)) {
            return false;
        }

        $this->db->select('*')
                ->from('product')
                ->where(array('product_category_id' => $iCategoryId, 'is_deleted' => 0));

        if ($bIsCheckActive) {
            $this->db->where('is_actived', ACTIVE);
        }

        $category = $this->db->get();

        if ($category->num_rows() > 0) {
            $oCategory = $category->result();
            $aCategory = array();
            foreach($oCategory as $value){
                $aCategory[] = $value;
            }
            
            return $aCategory;
        }

        return false;
    }

    public function addImage($sName) {
        if (empty($sName)) {
            return false;
        }

        $aImage = array(
            'name' => $sName,
            'date' => time()
        );

        if ((bool) $this->db->insert('image', $aImage)) {
            return $aImage;
        }

        return false;
    }

    private function _prepareArr(array $aArr = null, $isEdit = false) {
        if (empty($aArr)) {
            return false;
        }

        //Unset id to empty.
        if (!$isEdit) {
            unset($aArr['id']);
        }
        //Unset current page.
        unset($aArr['cur_page']);
        //Unset token...
        unset($aArr[$this->config->item('csrf_token_name')]);
        //$aArr['product_category_id'] = $aArr['category'];
        $aArr['product_category_id'] = 1;
        unset($aArr['category']);
        $aArr['language_id'] = $aArr['language'];
        unset($aArr['language']);
        $aArr['level_id'] = $aArr['level'];
        unset($aArr['level']);
        $aArr['date'] = time();
        $aArr['last_update'] = time();
        return $aArr;
    }

    public function gets($offset = 0, $numRow = 10) {
        $oProduct = $this->db->select('SQL_CALC_FOUND_ROWS p.id, p.name, p.summary, p.description,
            pc.name as category, p.total_view, p.total_like, p.date, p.image, sp.user_id as user_saved', false)
                ->from('product p')
                ->join('product_category pc', 'p.product_category_id = pc.id', 'left')
                ->join('language l', 'p.language_id = l.id', 'left')
                ->join('saved_product sp', 'p.id = sp.product_id', 'left')
                ->join('level le', 'p.level_id = le.id', 'left')
                ->where(array('p.is_actived' => 1, 'p.is_deleted' => 0))
                ->limit($numRow, $offset)
                ->order_by('order', 'asc')
                ->get();


        $aProduct = array();
        $this->load->library('encrypt');
        if ($oProduct->num_rows() > 0) {
            foreach ($oProduct->result() as $product) {
                $product->date = date('Y-m-d', $product->date);
                //$product->id = $this->encrypt->encode($product->id, $this->config->item('encode_id'));
                $aProduct[] = $product;
            }
        }

        $this->_itotal_rows = $this->db->query('SELECT FOUND_ROWS() AS count', false)->row()->count;

        return $aProduct;
    }

    public function getListAdmin($offset, $aSearch = null) {
        $this->db->select('SQL_CALC_FOUND_ROWS p.id, p.name, pc.name as category, p.date, p.is_actived as actived,
            p.is_featured as featured, p.order, l.name as language,
            le.name as level, p.date', false)
                ->from('product p')
                ->join('product_category pc', 'p.product_category_id = pc.id', 'left')
                ->join('language l', 'p.language_id = l.id', 'left')
                ->join('level le', 'p.level_id = le.id', 'left')
                ->where('p.is_deleted', 0);

        $aSearch = $this->prepareSearch($aSearch);

        foreach ($aSearch as $key => $val) {
            if (trim($val) == '') {
                continue;
            }

            switch ($key) {
                case 'category':
                case 'p.name':
                    $this->db->like($key, $val);
                    break;
                default :
                    $this->db->where($key, $val);
                    break;
            }
        }
        
        $iLimit = $this->session->userdata($this->config->item('ele_per_page'));
        
        if(!$iLimit){
            $iLimit = $this->config->item('per_page_admin');
        }
        
        $this->db->limit($iLimit, ($offset - 1) * $iLimit);

        foreach ($this->_aSort as $key => $value) {
            $this->db->order_by($this->_aRealSort[$key], $value);
        }

        $oProduct = $this->db->get();
        $aProduct = array();

        if ($oProduct->num_rows() > 0) {
            foreach ($oProduct->result() as $product) {
                $product->date = date('Y-m-d', $product->date);
                $aProduct[] = $product;
            }
        }

        $this->_itotal_rows = $this->db->query('SELECT FOUND_ROWS() AS count', false)->row()->count;

        return $aProduct;
    }

    public function prepareSearch($aSearch = null) {
        if (empty($aSearch)) {
            return array();
        }
        //Prepare search.
        $aReturn = array(
            'p.name' => $aSearch['name'],
            'p.is_actived' => $aSearch['is_actived'],
            'p.is_featured' => $aSearch['featured'],
            'pc.name' => $aSearch['category'],
            'p.order >=' => $aSearch['order']['from'],
            'p.order <=' => $aSearch['order']['to'],
            'p.date >=' => strtotime($aSearch['date']['from']),
            'p.date <=' => strtotime($aSearch['date']['to']),
            'p.language_id' => $aSearch['language'],
            'p.id >=' => $aSearch['id']['from'],
            'p.id <=' => $aSearch['id']['to']
        );

        if ($aSearch['is_actived'] == -1) {
            unset($aReturn['p.is_actived']);
        }

        if ($aSearch['featured'] == -1) {
            unset($aReturn['p.is_featured']);
        }

        if ($aSearch['is_actived'] == -1) {
            unset($aReturn['language_id']);
        }

        if ($aSearch['language'] == -1) {
            unset($aReturn['p.language_id']);
        }

        if(!$aReturn['p.date >=']){
			unset($aReturn['p.date >=']);
        }

        if(!$aReturn['p.date <=']){
        	unset($aReturn['p.date <=']);
        }

        return $aReturn;
    }

    public function sort($sCol = '') {
        if (empty($sCol)) {
            return false;
        }

        $sTypeSort = $this->prepareSort($sCol);

        if (!$sTypeSort) {
            $this->session->unset_userdata($this->config->item('sort'));
        } else {
            $this->session->set_userdata($this->config->item('sort'), $this->_aSort);
        }

        return $sTypeSort;
    }

    public function prepareSort($sCol) {
        if (empty($sCol)) {
            return false;
        }

        if (empty($this->_aSort[$sCol])) {
            $this->_aSort = array($sCol => 'desc');

            return 'desc';
        } else {
            $sTypeSort = $this->_aSort[$sCol] == 'desc' ? 'asc' : null;

            if (!$sTypeSort) {
                unset($this->_aSort[$sCol]);
            } else {
                $this->_aSort[$sCol] = $sTypeSort;
            }

            return $sTypeSort;
        }

        return false;
    }

    public function getSort() {
        $this->_aSort = $this->session->userdata($this->config->item('sort'));

        if (!(bool) $this->_aSort) {
            return array('order' => 'desc');
        }

        return $this->_aSort;
    }

    private function _load() {
        $this->_aSort = $this->getSort();
        $this->_aRealSort = array('name' => 'p.name', 'is_actived' => 'p.is_actived', 'is_featured' => 'p.is_featured',
            'category' => 'pc.name', 'level' => 'p.level_id', 'order' => 'p.order',
            'date' => 'p.date', 'lang' => 'l.name', 'id' => 'p.id');
    }

}

?>